<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/14
 * Time: 10:56
 */

class testAll extends MY_Controller{
    function __construct()
    {
        parent::__construct();
        $this->load->model('test_model');
        if($this->users['account'] != 'lyb'){
            js_goto('','无权限访问',1);
        }
    }

    public function index(){
        echo strtotime('2017-03-01');
    }
    /**
     * 匹配订单
     */
    public function MatchingOrder(){
        $data=ExcelToArray('./resource/uploadfiles/file/excels/tickets.xlsx');
        for($i=0;$i<count($data);$i++){
            $id=$this->test_model->GetOrder($data[$i][5],$data[$i][1]);
            if($id==''){
                $result[]=$data[$i];
            }
        }
        echo '无法匹配数据';
        gsh_output($result);
    }

    /**
     * 手动建产品
     */
    public function AddProduct(){
        $array=array (
            'user' => 'flowrepair',
            'key' => 'flowTokenPwd',
            'orders' => '{"repair_point":"es","website_origin":"0","create_time":"2016-08-31 14:42:31","quantity":"1","reference_order_number":"ES57C6D0B743EA2","repair_type":"1","merchant_num":"8","customer_name":"(david soria) david soria","customer_phone":"687452114","customer_email":"davidsoria_rca@hotmail.com","pickup_address":"ES zaragoza zaragoza 50007 av. america 24, 7","delivery_address":"ES zaragoza zaragoza 50007 av. america 24, 7","delivery_street_address":"av. america 24, 7","delivery_city":"zaragoza","delivery_state":"zaragoza","delivery_zipcode":"50007","delivery_country":"ES","pickup_service":1,"delivery_service":1,"storeOrShip":"1","rework_orderNum":"","nif":"25177739F","aws":"1","products_list":[{"productSku":"sku59899","category":"1","source_id_order":"73452680655843","quantity":"1","brandCustomerNum":24,"imei":"357895070074655","remark_customer":"Con fecha 3-6-2016, se me cay\\u00f3 el tel\\u00e9fono y se rompi\\u00f3 la pantalla, pero el tel\\u00e9fono funcionaba perfectamente. avise al vendedor de Aliexpores para que me informara sobre coste de reparaci\\u00f3n de la pantalla. Con fecha 23-6-2016 el micr\\u00f3fono dejo de funcionar. (tambi\\u00e9n  avise al vendedor), con fecha 19-7-2016 hice la ultima foto con c\\u00e1mara trasera, a partir de esa fecha ya no la reconoce. (tambi\\u00e9n  avise al vendedor).\\r\\n\\r\\nAdjunto videos: ultima foto, fallo c\\u00e1mara trasera y fallo en micr\\u00f3fono.\\r\\n\\r\\nhttps:\\/\\/youtu.be\\/S0EW0E2FduU\\r\\n\\r\\nhttps:\\/\\/youtu.be\\/c_ZccpPP-RE\\r\\n\\r\\nhttps:\\/\\/youtu.be\\/gLwgf43jjN8\\r\\n\\r\\nYa me dir\\u00e1n \\r\\nSaludos cordiales\\r\\nGracias.\\r\\n","defectDes":"Diagnostico","product_type":"2","product_brand":"Elephone","product_model":"P9000","model_id":"591","photo1":"ES57C6D0B743EA2_afd62eb38560e3e4_1.JPG","photo2":"ES57C6D0B743EA2_49a093e47c227593_2.JPG","photo3":"ES57C6D0B743EA2_e104cb41647a0f8e_3.JPG","photo4":"ES57C6D0B743EA2_d70366c4ce7d24d0_4.JPG","photo5":"ES57C6D0B743EA2_f804a5df1b30fa82_5.JPG","photo6":"ES57C6D0B743EA2_b8ac60c65d8dbdca_6.JPG","video":"https:\\/\\/youtu.be\\/S0EW0E2FduU","inWarranty_tr":"0"}]}',
        );
        $data=json_decode($array['orders'],true);
        $products = $data['products_list'];
        foreach ($products as $rs) {
            $productData['category_id'] = $rs['category'] ? $rs['category'] : 1;
            //产品数量
            $quantity = (int)$rs['product_quantity'];
            if ($quantity) {
                for ($i = 0; $i < $quantity; $i++) {
                    unset($productData['inWarranty_tr']);
                    $productData['productSku'] = $rs['productSku'];
                    $productData['attributes'] = $rs['attributes'];
                    $productData['source_id_order'] = $rs['source_id_order'];
                    $productData['product_brand'] = $rs['product_brand'];
                    $productData['product_model'] = $rs['product_model'];
                    $productData['model_id'] = $rs['model_id'];
                    $productData['customerRemark'] = $rs['remark_customer'];
                    $productData['defectDes'] = $rs['defectDes'];
                    $productData['imei'] = $rs['imei'];
                    $productData['brandCustomerNum'] = (int)$rs['brandCustomerNum'];
                    if (isset($rs['inWarranty_tr']) && is_numeric($rs['inWarranty_tr'])) {
                        $productData['inWarranty_tr'] = $rs['inWarranty_tr'];
                    }
                    $productData['photos1'] = $rs['photo1'];
                    $productData['photos2'] = $rs['photo2'];
                    $productData['photos3'] = $rs['photo3'];
                    $productData['photos4'] = $rs['photo4'];
                    $productData['photos5'] = $rs['photo5'];
                    $productData['photos6'] = $rs['photo6'];
                    $productData['videoUrl'] = $rs['video'];
                    $productData['create_time'] = $data['create_time'];
                    $productData['add_time'] = time();
                    $productData['add_user'] = 'system';
                    $pids[] = $this->common_model->insert('mt_product', $productData);
                }
            } else {
                $productData['productSku'] = $rs['productSku'];
                $productData['attributes'] = $rs['attributes'];
                $productData['source_id_order'] = $rs['source_id_order'];
                $productData['product_brand'] = $rs['product_brand'];
                $productData['product_model'] = $rs['product_model'];
                $productData['model_id'] = $rs['model_id'];
                $productData['customerRemark'] = $rs['remark_customer'];
                $productData['defectDes'] = $rs['defectDes'];
                $productData['imei'] = $rs['imei'];
                $productData['brandCustomerNum'] = (int)$rs['brandCustomerNum'];
                if (isset($rs['inWarranty_tr']) && is_numeric($rs['inWarranty_tr'])) {
                    $productData['inWarranty_tr'] = $rs['inWarranty_tr'];
                }
                $productData['photos1'] = $rs['photo1'];
                $productData['photos2'] = $rs['photo2'];
                $productData['photos3'] = $rs['photo3'];
                $productData['photos4'] = $rs['photo4'];
                $productData['photos5'] = $rs['photo5'];
                $productData['photos6'] = $rs['photo6'];
                $productData['videoUrl'] = $rs['video'];
                $productData['create_time'] = $data['create_time'];
                $productData['add_time'] = time();
                $productData['add_user'] = 'system';
                $pids[] = $this->common_model->insert('mt_product', $productData);
            }
        }
    }

    /**
     * 匹配产品
     */
    public function MatchingProduct(){
        $dataList=$this->test_model->GetOrderList();
        foreach($dataList as $row){
            $pData=$this->test_model->GetProduct($row['order_num']);
            if(!$pData){
                $excelData[]=array(
                    'id'=>$row['id'],
                    'order_num'=>$row['order_num'],
                    'source_oid'=>$row['source_oid'],
                    'create_time'=>$row['create_time'],
                    'add_time'=>date('Y-m-d H:i:s',$row['add_time'])
                );
            }
        }
        $fieldData=array(
            'id'=>'编号',
            'order_num'=>'订单号',
            'source_oid'=>'ticket',
            'create_time'=>'创建时间',
            'add_time'=>'OMS更新时间'
        );
        excel_output('loseData',$fieldData,$excelData);
    }

    /**
     * 产品数组
     * @return array
     */
    public function ProductArray(){
        $data=array(
        );
        return $data;
    }

    /**
     * 复制故障数据
     */
    public function CopyFaultData(){
        $faultData=$this->test_model->GetFault(1);
        foreach($faultData as $row){
            if($row['name_en'] != 'Fingerprint failure'){
                $data=array(
                    'name_ch'=>$row['name_ch'],
                    'name_en'=>$row['name_en'],
                    'category'=>2,
                    'add_user'=>$row['add_user'],
                    'add_time'=>time()
                );
                $this->test_model->AddFault($data);
            }
        }
    }

    /**
     * 导出订单数据
     */
    public function ExportProductData(){
        $orderData=$this->test_model->GetMerchantData();
        foreach($orderData as &$row){
            $start_qc_time=$this->test_model->GetOrderTrack($row['order_num'],2);
            $status_time_zj=$this->test_model->GetOrderTrackStatus($row['order_num']);
            $bg_time=$this->test_model->GetOrderTrack($row['order_num'],3);
            $bgOK_time=$this->test_model->GetOrderTrack($row['order_num'],4);
            $product_type_s=$this->test_model->GetProductType($row['order_num']);
            $row['add_time']=date('Y-m-d H:i:s',$row['add_time']);
            $row['product_type_s']=$product_type_s['name_ch'];
            $row['start_qc_time']=$start_qc_time['add_time']?date('Y-m-d H:i:s',$start_qc_time['add_time']):'';
            $row['status_name_zj']=$status_time_zj['name_ch']?$status_time_zj['name_ch']:'待接收';
            $row['status_time_zj']=$status_time_zj['add_time']?date('Y-m-d H:i:s',$status_time_zj['add_time']):'';
            $row['bg_time']=$bg_time['add_time']?date('Y-m-d H:i:s',$bg_time['add_time']):'';
            $row['bgOK_time']=$bgOK_time['add_time']?date('Y-m-d H:i:s',$bgOK_time['add_time']):'';
        }
        unset($row);
        $fieldData=array(
            'order_num'=>'订单号',
            'id'=>'产品ID',
            'product_type_s'=>'产品品类',
            'add_time'=>'建单时间',
            'start_qc_time'=>'开始处理时间（拆包质检）',
            'status_name_zj'=>'最近状态',
            'status_time_zj'=>'最近状态时间',
            'bg_time'=>'报价时间',
            'bgOK_time'=>'同意报价时间'
        );
        excel_output('orderData_Aukey',$fieldData,$orderData);
    }

    public function GetMaintenancePlannerData($id=4){
        $data=$this->test_model->GetMaintenancePlannerData($id);
        foreach($data as &$row){
            $row['add_time']=date('Y-m-d',$row['add_time']);
            $row['name']='李阳';
        }
        unset($row);
        $fieldData=array(
            'order_num'=>'订单号',
            'add_time'=>'产品ID',
            'name'=>'姓名',
        );
        excel_output('productData_liyang',$fieldData,$data);
    }

    /**
     * 获取资金遗漏数据
     */
    public function GetMoneyOmitData(){
        $add=array();
        $data=$this->test_model->GetMoneyOmitData();
        foreach($data as $row){
            $brandCustomerNum=$this->test_model->QueryBrandC($row['order_num']);
            $moneyOrder=$this->test_model->QueryMoneyOrder($row['order_num'],$brandCustomerNum['brandCustomerNum']);
            if($moneyOrder['orderId']) {
                echo $moneyOrder['orderId'].'##########';
            }else{
                $clineInfo = $this->test_model->GetClineInfo($brandCustomerNum['brandCustomerNum']);
                //判断是否需要货币转换
                $money = $row['grandTotalMerchant'];
                if (strcasecmp($row['currency_code'], $clineInfo['CurrencyIsoCode'])) {
                    $money = currency_service($row['currency_code'], $clineInfo['CurrencyIsoCode'], $row['grandTotalMerchant']);
                }
                $arr = array(
                    'customers_id' => $brandCustomerNum['brandCustomerNum'],
                    'time' => $row['add_time'],
                    'orderId' => $row['order_num'],
                    'money' => -$money,
                    'currency' => $clineInfo['CurrencyIsoCode'],
                    'country_code' => $row['point'],
                );
                $add[]=$arr;
                /*//判断余额是否透支完毕
                $facilityExtent = $clineInfo['facilityExtent'] + ($clineInfo['Balances'] - $money);
                if ($facilityExtent >= 0) {
                    //添加存款记录并返回ID号
                    $id = $this->test_model->AddDepositRecord($arr);
                    //更新余额
                    $this->test_model->UpdateBalances_new($row['merchant_num'],-$money);
                }*/
            }
        }
        gsh_output($add);
    }
    public function testDHL(){
        $this->load->library('DHL');
        $dhl = new DHL();
        //receiver details
        $customer_details = array(
            'first_name'    => 'Tobias',
            'last_name'     => 'Redmann',
            'c/o'           => '',
            'street_name'   => 'Hocksteinweg',
            'street_number' => '11',
            'country'       => 'germany',
            'countryISOCode'   => 'DE',
            'zip'           => '14165',
            'city'          => 'Berlin',
            'addressAddition' => '',
            'email'           => 'info@tomrepair.de',
            'phone'           => '+49421123456',
            'contact_person'  => 'Tobias',
            'customerReference'  => 'WX000007'

        );
        //$response = $dhl->getVersion();
        $response = $dhl->createNationalShipment($customer_details);
        if($response !== false) {
            echo "<pre>";
            var_dump($response);
            echo "</pre>";
        } else {
            echo "<br>errors: ";
            var_dump($dhl->errors);
        }
    }
    public function getTrack(){
        $data=$this->test_model->getTrack('es',strtotime('2016-12-05'),strtotime('2016-12-06'));
        foreach($data as &$row){
            $row['add_time']=date('Y-m-d H:i:s',$row['add_time']);
        }
        unset($row);
        $fieldData=array(
            'order_num'=>'订单号',
            'pid'=>'产品ID',
            'name_ch'=>'状态',
            'add_time'=>'时间',
            'point'=>'站点',
        );
        excel_output('data',$fieldData,$data);
    }

    /**
     * 更新客户信息
     */
    public function updateClineInfo(){
        $data=ExcelToArray('./resource/uploadfiles/file/excels/product.xlsx');
        for($i=0;$i<count($data);$i++){
            $addData=array(
                'bid'=>$data[$i][1],
                'tid'=>$data[$i][2],
                'name'=>$data[$i][3],
                'sort_id'=>$data[$i][4],
                'authorization'=>$data[$i][5],
                'mid'=>$data[$i][6],
                'site'=>7,
                'warranty_type'=>$data[$i][8]==null?0:$data[$i][8],
                'is_sync'=>$data[$i][9],
                'series_id'=>$data[$i][10],
                'custom_id'=>$data[$i][11],
            );
            $this->common_model->insert('site_product_model',$addData);
        }
    }

    /**
     * 测试机器人
     */
    public function testJQ(){
        $url="https://oapi.dingtalk.com/robot/send?access_token=759a5a351c91ca499ad9f98e43c7f9c38ac60a07b14ff54c2a7450472c52a5b0";
        //$url="https://oapi.dingtalk.com/robot/send?access_token=ba607cdea6b54538a4b98b709861176dd3e30f13d148b49daabb866b7dffa282";
        $data=array(
            'msgtype'=>'text',
            'text'=>array(
                'content'=>'四季豆腊肉(辣跳楼)'
            ),
            'at'=>array(
                'isAtAll'=>1
            )
        );
        $st=TomRepairCurlPost($url,$data);
        gsh_output($st);
    }

    /**
     * 获取产品导出数据
     */
    public function getProductExport(){
        $data=$this->test_model->getProductExport();
        $damage=array(1=>'全新',2=>'九成新',4=>'五成新',6=>'严重损坏');
        foreach($data as &$row){
            $row['add_time']=date('Y-m-d H:i:s',$row['add_time']);
            $row['physicalAppearance']=$damage[$row['physicalAppearance']];
        }
        unset($row);
        $filedData=array(
            'order_num'=>'维修单号',
            'add_time'=>'入库时间',
            'physicalAppearance'=>'成色',
            'source_oid'=>'来源单号',
            'productSku'=>'物料代码',
            'point'=>'维修站点',
        );
        excel_output('orderData',$filedData,$data);
    }

    /**
     * 导出产品分类
     */
    public function exportProductClass(){
        $data=$this->common_model->selectCustom('site_product_model','','site');
        $siteArray=array(1=>'ES',2=>'UK',3=>'DE',4=>'RU',5=>'US',6=>'OMS',7=>'FR');
        foreach($data as &$row){
            if($row['custom_id']){
                $tid=$row['custom_id'];
            }else{
                $tid=$row['tid'];
            }
            $tData=$this->common_model->selectFirst('site_product_type',array('site'=>$row['site'],'tid'=>$tid));
            $bData=$this->common_model->selectFirst('site_product_brand',array('site'=>$row['site'],'tid'=>$tid,'bid'=>$row['bid']));
            $row['tName']=$tData['name'];
            $row['bName']=$bData['name'];
            $row['siteName']=$siteArray[$row['site']];
        }
        unset($row);
        $fieldData=array(
            'siteName'=>'站点',
            'tName'=>'类型',
            'bName'=>'品牌',
            'name'=>'型号',
        );
        excel_output('data',$fieldData,$data);
    }

    /**
     * 导出维修中等待配件产品
     */
    public  function exportAwaitParts(){
        $data=$this->common_model->selectCustom('mt_product',array('status_id'=>8));
        foreach($data as &$row){
            $partsList=$this->common_model->selectCustom('mt_product_parts',array('pid'=>$row['id']));
            $pArray=array();
            foreach($partsList as $p){
                $pArray[]=$p['name'];
            }
            $row['partsList']=implode('#',$pArray);
        }
        unset($row);
        $fieldData=array(
            'order_num'=>'订单号',
            'product_model'=>'产品型号',
            'partsList'=>'配件'
        );
        excel_output('data',$fieldData,$data);
    }
    public function testHL(){
        echo strtotime('2017-03-31');
    }

    public function testHQ(){
        $this->load->library('GlobalEGrow');
        $globalEGrow=new GlobalEGrow();
        $data=$globalEGrow->transferAddress(44411);
        gsh_output($data);
    }

    /**
     * 导出财务对账单
     */
    public function exportStatement(){
        $time=strtotime('2017-04-30');
        $client=array(445=>'doogee 电商部门',1176=>'doogee荷兰电商',1441=>'doogee批发售后部',1446=>'doogee madrid wholesaler',28=>'doogee');
        $data=$this->common_model->selectFirst('mt_product',array('add_time < '=>$time,'status_id > '=>5));
    }

    /**
     * 复制分类数据 慎用，一定要保证复制站点三大类没有任何数据
     * @param string $item
     */
    public function copyClass($item=''){
        $msg['msg']='空数据';
        if($item) {
            $classData=explode('_',$item);
            $siteId=$classData[0];
            $copySite=$classData[1];
            $numData=array(1,2,3,4,5,6,7,8,9,10,11,12);
            if(in_array($siteId,$numData) && in_array($copySite,$numData) && $siteId != $copySite) {
                $typeData = $this->common_model->selectCustom('site_product_type', array('site' => $siteId));
                $brandData = $this->common_model->selectCustom('site_product_brand', array('site' => $siteId));
                $modelData = $this->common_model->selectCustom('site_product_model', array('site' => $siteId));
                if($typeData) {
                    foreach ($typeData as $trow) {
                        $data = array(
                            'name' => $trow['name'],
                            'name_en' => $trow['name_en'],
                            'site' => $copySite,
                            'sort_id' => $trow['sort_id'],
                            'authorization' => $trow['authorization'],
                            'tid' => $trow['tid'],
                            'logo' => $trow['logo'],
                            'is_sync' => $trow['is_sync'],
                            'is_custom' => $trow['is_custom'],
                            'custom_id' => $trow['custom_id']
                        );
                        $this->common_model->insert('site_product_type', $data);
                    }
                    $msg['msg'][]='产品类复制完成';
                }
                if($brandData) {
                    foreach ($brandData as $brow) {
                        $data = array(
                            'name' => $brow['name'],
                            'tid' => $brow['tid'],
                            'sort_id' => $brow['sort_id'],
                            'authorization' => $brow['authorization'],
                            'bid' => $brow['bid'],
                            'site' => $copySite,
                            'logo' => $brow['logo'],
                            'is_sync' => $brow['is_sync'],
                            'series_id' => $brow['series_id'],
                            'custom_id' => $brow['custom_id'],
                        );
                        $this->common_model->insert('site_product_brand', $data);
                    }
                    $msg['msg'][]='品牌类复制完成';
                }
                if($modelData) {
                    foreach ($modelData as $mrow) {
                        $data = array(
                            'bid' => $mrow['bid'],
                            'tid' => $mrow['tid'],
                            'name' => $mrow['name'],
                            'sort_id' => $mrow['sort_id'],
                            'authorization' => $mrow['authorization'],
                            'mid' => $mrow['mid'],
                            'site' => $copySite,
                            'warranty_type' => $mrow['warranty_type'],
                            'is_sync' => $mrow['is_sync'],
                            'series_id' => $mrow['series_id'],
                            'custom_id'=> $mrow['custom_id']
                        );
                        $this->common_model->insert('site_product_model', $data);
                    }
                    $msg['msg'][]='型号类复制完成';
                }
            }else{
                $msg['msg']='参数错误';
            }
        }else{
            $msg['msg']='缺少参数';
        }
        gsh_output($msg);
    }
}